<template>
  <view class="scan" @click="handleClick">
    <slot>
      <image src="@/static/icon6.png" class="img"></image>
      <view class="scan__right">
        <text class="title" :class="{ active: palletCode }">
          {{ palletCode ? palletCode : tip }}
        </text>
        <m-button plain shape="round" size="md" width="225rpx" height="76rpx" v-if="showBtn">
          <span style="font-size: 32rpx">{{ scanText }}</span>
        </m-button>
      </view>
    </slot>
  </view>
</template>

<script>
export default {
  props: {
    palletCode: {
      type: String,
      default: '',
    },
    tip: {
      type: String,
      default: '托盘码等待中...',
    },
    showBtn: {
      type: Boolean,
      default: true,
    },
    scan: {
      type: Boolean,
      default: false,
    },
    scanText: {
      type: String,
      default: '扫描托盘码',
    },
    validate: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      barcodeModel: null,
    }
  },
  mounted() {
    if (this.scan) {
      this.barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
      this.barcodeModel.initScan()
      uni.requireNativePlugin('globalEvent').addEventListener('iDataBarcodeEvent', async ({ barcode }) => {
        if (this.validate && !(await this.validate())) {
          return
        }

        this.$emit('change', barcode)
      })
    }
  },
  methods: {
    async handleClick() {
      if (this.validate && !(await this.validate())) {
        return
      }
      this.barcodeModel.scanStart(() => {
        console.log(7)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.scan {
  display: flex;
  align-items: center;
  margin: 30rpx;
  .img {
    width: 118rpx;
    height: 123rpx;
    border-radius: 50%;
    box-shadow: 0rpx 0rpx 60rpx 0rpx rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20rpx;
  }
  .title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    display: flex;
    color: #333;
  }
  &__right {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 1;
    .button {
      background: transparent;
    }
  }
}
</style>
